{% extends 'base.html' %}
{% load static %}

{% block title %}任务状态 - CFS Web System{% endblock %}

{% block page_type %}task-status{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item active">任务状态</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 页面标题 -->
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-tasks me-2"></i>任务状态</h2>
            <div class="btn-group">
                <button type="button" class="btn btn-outline-primary" onclick="refreshTasks()">
                    <i class="fas fa-sync-alt"></i> 刷新
                </button>
                <button type="button" class="btn btn-outline-danger" onclick="clearCompletedTasks()">
                    <i class="fas fa-trash"></i> 清理已完成
                </button>
                <a href="{% url 'data_processing:data_generation' %}" class="btn btn-success">
                    <i class="fas fa-plus"></i> 新建任务
                </a>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 任务统计 -->
    <div class="col-12 mb-4">
        <div class="row" id="task-stats">
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-primary">
                            <i class="fas fa-list"></i>
                        </div>
                        <h3 class="stat-number" id="total-tasks">0</h3>
                        <p class="stat-label">总任务数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-warning">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h3 class="stat-number" id="pending-tasks">0</h3>
                        <p class="stat-label">等待中</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-info">
                            <i class="fas fa-spinner"></i>
                        </div>
                        <h3 class="stat-number" id="running-tasks">0</h3>
                        <p class="stat-label">处理中</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-success">
                            <i class="fas fa-check"></i>
                        </div>
                        <h3 class="stat-number" id="completed-tasks">0</h3>
                        <p class="stat-label">已完成</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 任务列表 -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-list me-2"></i>任务列表
                    </h5>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary filter-btn active" data-filter="all">
                            全部
                        </button>
                        <button type="button" class="btn btn-outline-warning filter-btn" data-filter="pending">
                            等待中
                        </button>
                        <button type="button" class="btn btn-outline-info filter-btn" data-filter="running">
                            处理中
                        </button>
                        <button type="button" class="btn btn-outline-success filter-btn" data-filter="completed">
                            已完成
                        </button>
                        <button type="button" class="btn btn-outline-danger filter-btn" data-filter="failed">
                            失败
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <div id="task-list-container">
                    <!-- 任务列表将通过AJAX加载 -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- 任务详情 -->
    <div class="col-lg-4">
        <div class="card" id="task-detail-card" style="display: none;">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>任务详情
                </h6>
            </div>
            <div class="card-body" id="task-detail-content">
                <!-- 任务详情将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 系统状态 -->
        <div class="card mt-4">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-server me-2"></i>系统状态
                </h6>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="system-metric">
                            <div class="metric-value" id="cpu-usage">--</div>
                            <div class="metric-label">CPU使用率</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="system-metric">
                            <div class="metric-value" id="memory-usage">--</div>
                            <div class="metric-label">内存使用率</div>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="row text-center">
                    <div class="col-6">
                        <div class="system-metric">
                            <div class="metric-value" id="queue-size">--</div>
                            <div class="metric-label">队列长度</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="system-metric">
                            <div class="metric-value" id="worker-count">--</div>
                            <div class="metric-label">工作进程</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div class="modal fade" id="taskDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-info-circle me-2"></i>任务详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="modal-task-detail">
                <!-- 详细信息将通过JavaScript加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="download-result-btn" style="display: none;">
                    <i class="fas fa-download"></i> 下载结果
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 日志查看模态框 -->
<div class="modal fade" id="logModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-file-alt me-2"></i>任务日志
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary log-level-btn active" data-level="all">
                            全部
                        </button>
                        <button type="button" class="btn btn-outline-info log-level-btn" data-level="info">
                            信息
                        </button>
                        <button type="button" class="btn btn-outline-warning log-level-btn" data-level="warning">
                            警告
                        </button>
                        <button type="button" class="btn btn-outline-danger log-level-btn" data-level="error">
                            错误
                        </button>
                    </div>
                    <div>
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="refreshLogs()">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearLogs()">
                            <i class="fas fa-eraser"></i> 清空
                        </button>
                    </div>
                </div>
                <div id="log-content" class="log-viewer">
                    <!-- 日志内容将通过JavaScript加载 -->
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 页面状态管理
const pageState = {
    currentFilter: 'all',
    selectedTask: null,
    autoRefresh: true,
    refreshInterval: null
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeTaskStatus();
});

// 初始化任务状态页面
function initializeTaskStatus() {
    // 加载任务列表
    loadTasks();
    
    // 加载系统状态
    loadSystemStatus();
    
    // 绑定过滤器事件
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            setFilter(this.dataset.filter);
        });
    });
    
    // 绑定日志级别过滤事件
    const logLevelBtns = document.querySelectorAll('.log-level-btn');
    logLevelBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            setLogLevel(this.dataset.level);
        });
    });
    
    // 启动自动刷新
    startAutoRefresh();
    
    // 检查URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const taskId = urlParams.get('task_id');
    if (taskId) {
        // 延迟选择任务，等待列表加载完成
        setTimeout(() => {
            selectTask(taskId);
        }, 1000);
    }
}

// 加载任务列表
function loadTasks() {
    const container = document.getElementById('task-list-container');
    CFS.utils.showLoading(container, '加载任务列表...');
    
    const params = new URLSearchParams();
    if (pageState.currentFilter !== 'all') {
        params.append('status', pageState.currentFilter);
    }
    
    fetch(`/excel-processor/ajax/tasks/?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderTaskList(data.tasks);
                updateTaskStats(data.stats);
            } else {
                container.innerHTML = '<div class="alert alert-danger m-3">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger m-3">加载失败: ' + error.message + '</div>';
        });
}

// 渲染任务列表
function renderTaskList(tasks) {
    const container = document.getElementById('task-list-container');
    
    if (tasks.length === 0) {
        container.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">暂无任务</h5>
                <p class="text-muted mb-3">还没有任何处理任务。</p>
                <a href="/data-generation/" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 创建任务
                </a>
            </div>
        `;
        return;
    }
    
    const html = tasks.map(task => `
        <div class="task-item ${task.id === pageState.selectedTask ? 'selected' : ''}" 
             data-task-id="${task.id}" onclick="selectTask('${task.id}')">
            <div class="d-flex align-items-center p-3">
                <div class="flex-shrink-0">
                    <div class="status-indicator status-${task.status}">
                        ${getStatusIcon(task.status)}
                    </div>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-1">${task.name}</h6>
                            <p class="text-muted mb-1">${task.template_name || '未知模板'}</p>
                            <small class="text-muted">
                                <i class="fas fa-clock me-1"></i>${CFS.utils.formatDateTime(task.created_at)}
                            </small>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-${getStatusColor(task.status)}">
                                ${getStatusText(task.status)}
                            </span>
                            ${task.progress !== undefined ? `
                                <div class="progress mt-1" style="width: 80px; height: 4px;">
                                    <div class="progress-bar" style="width: ${task.progress}%"></div>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                    ${task.status === 'running' && task.current_step ? `
                        <div class="mt-2">
                            <small class="text-info">
                                <i class="fas fa-cog fa-spin me-1"></i>${task.current_step}
                            </small>
                        </div>
                    ` : ''}
                </div>
                <div class="flex-shrink-0 ms-3">
                    <div class="btn-group btn-group-sm">
                        ${task.status === 'completed' ? `
                            <button type="button" class="btn btn-outline-success" 
                                    onclick="downloadResult('${task.id}'); event.stopPropagation();">
                                <i class="fas fa-download"></i>
                            </button>
                        ` : ''}
                        <button type="button" class="btn btn-outline-primary" 
                                onclick="showTaskDetail('${task.id}'); event.stopPropagation();">
                            <i class="fas fa-info"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" 
                                onclick="showTaskLogs('${task.id}'); event.stopPropagation();">
                            <i class="fas fa-file-alt"></i>
                        </button>
                        ${task.status === 'running' ? `
                            <button type="button" class="btn btn-outline-danger" 
                                    onclick="cancelTask('${task.id}'); event.stopPropagation();">
                                <i class="fas fa-stop"></i>
                            </button>
                        ` : `
                            <button type="button" class="btn btn-outline-danger" 
                                    onclick="deleteTask('${task.id}'); event.stopPropagation();">
                                <i class="fas fa-trash"></i>
                            </button>
                        `}
                    </div>
                </div>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = html;
}

// 更新任务统计
function updateTaskStats(stats) {
    document.getElementById('total-tasks').textContent = stats.total || 0;
    document.getElementById('pending-tasks').textContent = stats.pending || 0;
    document.getElementById('running-tasks').textContent = stats.running || 0;
    document.getElementById('completed-tasks').textContent = stats.completed || 0;
}

// 选择任务
function selectTask(taskId) {
    pageState.selectedTask = taskId;
    
    // 更新选中状态
    const taskItems = document.querySelectorAll('.task-item');
    taskItems.forEach(item => {
        item.classList.toggle('selected', item.dataset.taskId === taskId);
    });
    
    // 显示任务详情
    document.getElementById('task-detail-card').style.display = 'block';
    loadTaskDetail(taskId);
}

// 加载任务详情
function loadTaskDetail(taskId) {
    const container = document.getElementById('task-detail-content');
    CFS.utils.showLoading(container, '加载任务详情...');
    
    fetch(`/excel-processor/ajax/tasks/${taskId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderTaskDetail(data.task);
            } else {
                container.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
        });
}

// 渲染任务详情
function renderTaskDetail(task) {
    const container = document.getElementById('task-detail-content');
    
    const html = `
        <div class="task-detail">
            <h6>${task.name}</h6>
            <p class="text-muted mb-3">${task.description || '暂无描述'}</p>
            
            <div class="row mb-3">
                <div class="col-6">
                    <small class="text-muted">状态:</small><br>
                    <span class="badge bg-${getStatusColor(task.status)}">
                        ${getStatusText(task.status)}
                    </span>
                </div>
                <div class="col-6">
                    <small class="text-muted">进度:</small><br>
                    <span class="fw-bold">${task.progress || 0}%</span>
                </div>
            </div>
            
            ${task.progress !== undefined ? `
                <div class="mb-3">
                    <div class="progress">
                        <div class="progress-bar" style="width: ${task.progress}%"></div>
                    </div>
                </div>
            ` : ''}
            
            <div class="mb-3">
                <small class="text-muted">模板:</small><br>
                <span class="fw-bold">${task.template_name || '未知模板'}</span>
            </div>
            
            <div class="mb-3">
                <small class="text-muted">源文件:</small><br>
                <span class="fw-bold">${task.source_files ? task.source_files.length : 0} 个文件</span>
            </div>
            
            <div class="row mb-3">
                <div class="col-6">
                    <small class="text-muted">创建时间:</small><br>
                    <span class="fw-bold">${CFS.utils.formatDateTime(task.created_at)}</span>
                </div>
                <div class="col-6">
                    <small class="text-muted">更新时间:</small><br>
                    <span class="fw-bold">${CFS.utils.formatDateTime(task.updated_at)}</span>
                </div>
            </div>
            
            ${task.current_step ? `
                <div class="mb-3">
                    <small class="text-muted">当前步骤:</small><br>
                    <span class="text-info">${task.current_step}</span>
                </div>
            ` : ''}
            
            ${task.error_message ? `
                <div class="alert alert-danger">
                    <small class="text-muted">错误信息:</small><br>
                    ${task.error_message}
                </div>
            ` : ''}
            
            <div class="d-grid gap-2">
                ${task.status === 'completed' ? `
                    <button type="button" class="btn btn-success" onclick="downloadResult('${task.id}')">
                        <i class="fas fa-download"></i> 下载结果
                    </button>
                ` : ''}
                <button type="button" class="btn btn-outline-primary" onclick="showTaskLogs('${task.id}')">
                    <i class="fas fa-file-alt"></i> 查看日志
                </button>
                ${task.status === 'running' ? `
                    <button type="button" class="btn btn-outline-danger" onclick="cancelTask('${task.id}')">
                        <i class="fas fa-stop"></i> 取消任务
                    </button>
                ` : `
                    <button type="button" class="btn btn-outline-danger" onclick="deleteTask('${task.id}')">
                        <i class="fas fa-trash"></i> 删除任务
                    </button>
                `}
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

// 加载系统状态
function loadSystemStatus() {
    fetch('/analytics/ajax/system-status/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateSystemStatus(data.status);
            }
        })
        .catch(error => {
            console.error('加载系统状态失败:', error);
        });
}

// 更新系统状态
function updateSystemStatus(status) {
    document.getElementById('cpu-usage').textContent = status.cpu_usage ? status.cpu_usage + '%' : '--';
    document.getElementById('memory-usage').textContent = status.memory_usage ? status.memory_usage + '%' : '--';
    document.getElementById('queue-size').textContent = status.queue_size || '--';
    document.getElementById('worker-count').textContent = status.worker_count || '--';
}

// 设置过滤器
function setFilter(filter) {
    pageState.currentFilter = filter;
    
    // 更新按钮状态
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.filter === filter);
    });
    
    // 重新加载任务列表
    loadTasks();
}

// 设置日志级别
function setLogLevel(level) {
    // 更新按钮状态
    const logLevelBtns = document.querySelectorAll('.log-level-btn');
    logLevelBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.level === level);
    });
    
    // 过滤日志内容
    filterLogContent(level);
}

// 过滤日志内容
function filterLogContent(level) {
    const logEntries = document.querySelectorAll('.log-entry');
    logEntries.forEach(entry => {
        if (level === 'all' || entry.dataset.level === level) {
            entry.style.display = 'block';
        } else {
            entry.style.display = 'none';
        }
    });
}

// 显示任务详情模态框
function showTaskDetail(taskId) {
    const modal = new bootstrap.Modal(document.getElementById('taskDetailModal'));
    const container = document.getElementById('modal-task-detail');
    
    CFS.utils.showLoading(container, '加载任务详情...');
    modal.show();
    
    fetch(`/excel-processor/ajax/tasks/${taskId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderModalTaskDetail(data.task);
            } else {
                container.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
        });
}

// 渲染模态框任务详情
function renderModalTaskDetail(task) {
    const container = document.getElementById('modal-task-detail');
    const downloadBtn = document.getElementById('download-result-btn');
    
    // 显示/隐藏下载按钮
    if (task.status === 'completed') {
        downloadBtn.style.display = 'inline-block';
        downloadBtn.onclick = () => downloadResult(task.id);
    } else {
        downloadBtn.style.display = 'none';
    }
    
    const html = `
        <div class="row">
            <div class="col-md-6">
                <h6>基本信息</h6>
                <table class="table table-sm">
                    <tr><td>任务名称:</td><td>${task.name}</td></tr>
                    <tr><td>状态:</td><td><span class="badge bg-${getStatusColor(task.status)}">${getStatusText(task.status)}</span></td></tr>
                    <tr><td>进度:</td><td>${task.progress || 0}%</td></tr>
                    <tr><td>模板:</td><td>${task.template_name || '未知模板'}</td></tr>
                    <tr><td>源文件数:</td><td>${task.source_files ? task.source_files.length : 0}</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>时间信息</h6>
                <table class="table table-sm">
                    <tr><td>创建时间:</td><td>${CFS.utils.formatDateTime(task.created_at)}</td></tr>
                    <tr><td>开始时间:</td><td>${task.started_at ? CFS.utils.formatDateTime(task.started_at) : '未开始'}</td></tr>
                    <tr><td>完成时间:</td><td>${task.completed_at ? CFS.utils.formatDateTime(task.completed_at) : '未完成'}</td></tr>
                    <tr><td>耗时:</td><td>${task.duration || '计算中...'}</td></tr>
                </table>
            </div>
        </div>
        
        ${task.description ? `
            <div class="mt-3">
                <h6>描述</h6>
                <p>${task.description}</p>
            </div>
        ` : ''}
        
        ${task.processing_options ? `
            <div class="mt-3">
                <h6>处理选项</h6>
                <div class="row">
                    <div class="col-md-6">
                        <small class="text-muted">输出格式:</small> ${task.processing_options.output_format || 'xlsx'}<br>
                        <small class="text-muted">分组依据:</small> ${task.processing_options.group_by || '无'}<br>
                    </div>
                    <div class="col-md-6">
                        <small class="text-muted">合并工作表:</small> ${task.processing_options.merge_sheets ? '是' : '否'}<br>
                        <small class="text-muted">包含汇总:</small> ${task.processing_options.include_summary ? '是' : '否'}<br>
                    </div>
                </div>
            </div>
        ` : ''}
        
        ${task.current_step ? `
            <div class="mt-3">
                <h6>当前步骤</h6>
                <div class="alert alert-info">
                    <i class="fas fa-cog fa-spin me-2"></i>${task.current_step}
                </div>
            </div>
        ` : ''}
        
        ${task.error_message ? `
            <div class="mt-3">
                <h6>错误信息</h6>
                <div class="alert alert-danger">
                    ${task.error_message}
                </div>
            </div>
        ` : ''}
    `;
    
    container.innerHTML = html;
}

// 显示任务日志
function showTaskLogs(taskId) {
    const modal = new bootstrap.Modal(document.getElementById('logModal'));
    const container = document.getElementById('log-content');
    
    CFS.utils.showLoading(container, '加载任务日志...');
    modal.show();
    
    fetch(`/excel-processor/ajax/tasks/${taskId}/logs/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderTaskLogs(data.logs);
            } else {
                container.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
        });
}

// 渲染任务日志
function renderTaskLogs(logs) {
    const container = document.getElementById('log-content');
    
    if (logs.length === 0) {
        container.innerHTML = '<div class="text-center py-3 text-muted">暂无日志记录</div>';
        return;
    }
    
    const html = logs.map(log => `
        <div class="log-entry" data-level="${log.level}">
            <span class="log-time">${CFS.utils.formatDateTime(log.timestamp)}</span>
            <span class="log-level log-level-${log.level}">${log.level.toUpperCase()}</span>
            <span class="log-message">${log.message}</span>
        </div>
    `).join('');
    
    container.innerHTML = html;
    
    // 滚动到底部
    container.scrollTop = container.scrollHeight;
}

// 下载结果
function downloadResult(taskId) {
    window.open(`/excel-processor/download/${taskId}/`, '_blank');
}

// 取消任务
function cancelTask(taskId) {
    if (!confirm('确定要取消这个任务吗？')) {
        return;
    }
    
    fetch(`/excel-processor/ajax/tasks/${taskId}/cancel/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('任务已取消', 'success');
            loadTasks();
        } else {
            CFS.utils.showNotification('取消失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('取消失败: ' + error.message, 'error');
    });
}

// 删除任务
function deleteTask(taskId) {
    if (!confirm('确定要删除这个任务吗？此操作不可恢复。')) {
        return;
    }
    
    fetch(`/excel-processor/ajax/tasks/${taskId}/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('任务已删除', 'success');
            loadTasks();
            
            // 如果删除的是当前选中的任务，隐藏详情卡片
            if (pageState.selectedTask === taskId) {
                document.getElementById('task-detail-card').style.display = 'none';
                pageState.selectedTask = null;
            }
        } else {
            CFS.utils.showNotification('删除失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('删除失败: ' + error.message, 'error');
    });
}

// 刷新任务列表
function refreshTasks() {
    loadTasks();
    loadSystemStatus();
    CFS.utils.showNotification('已刷新', 'info');
}

// 清理已完成的任务
function clearCompletedTasks() {
    if (!confirm('确定要清理所有已完成的任务吗？此操作不可恢复。')) {
        return;
    }
    
    fetch('/excel-processor/ajax/tasks/clear-completed/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(`已清理 ${data.count} 个任务`, 'success');
            loadTasks();
        } else {
            CFS.utils.showNotification('清理失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('清理失败: ' + error.message, 'error');
    });
}

// 刷新日志
function refreshLogs() {
    if (pageState.selectedTask) {
        showTaskLogs(pageState.selectedTask);
    }
}

// 清空日志
function clearLogs() {
    document.getElementById('log-content').innerHTML = '';
}

// 启动自动刷新
function startAutoRefresh() {
    if (pageState.refreshInterval) {
        clearInterval(pageState.refreshInterval);
    }
    
    pageState.refreshInterval = setInterval(() => {
        if (pageState.autoRefresh) {
            loadTasks();
            loadSystemStatus();
        }
    }, 30000); // 30秒刷新一次
}

// 停止自动刷新
function stopAutoRefresh() {
    if (pageState.refreshInterval) {
        clearInterval(pageState.refreshInterval);
        pageState.refreshInterval = null;
    }
}

// 工具函数
function getStatusIcon(status) {
    const icons = {
        'pending': '<i class="fas fa-clock"></i>',
        'running': '<i class="fas fa-spinner fa-spin"></i>',
        'completed': '<i class="fas fa-check"></i>',
        'failed': '<i class="fas fa-times"></i>',
        'cancelled': '<i class="fas fa-ban"></i>'
    };
    return icons[status] || '<i class="fas fa-question"></i>';
}

function getStatusColor(status) {
    const colors = {
        'pending': 'warning',
        'running': 'info',
        'completed': 'success',
        'failed': 'danger',
        'cancelled': 'secondary'
    };
    return colors[status] || 'secondary';
}

function getStatusText(status) {
    const texts = {
        'pending': '等待中',
        'running': '处理中',
        'completed': '已完成',
        'failed': '失败',
        'cancelled': '已取消'
    };
    return texts[status] || '未知';
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});
</script>
{% endblock %}